package com.societyGames.flashForms
{
import flash.display.Sprite;
import flash.events.MouseEvent;

public class WindowsContainer extends Sprite
{
  //private var _desiredWidth:Number;
  //private var _desiredHeight:Number;
  private var _windows:Array = [];

  public function addWindow(window:Window):void
  {
    if (window == null)
    {
      throw new ArgumentError("Argument \"window\" cannot be null.");
    }
    if (_windows.indexOf(window) == -1)
    {
      var oldParent:WindowsContainer = window.parent as WindowsContainer;
      if (oldParent != null)
      {
        oldParent.removeWindow(window);
      }
      this._windows.push(window);
      this.addChild(window);
      window.addEventListener(MouseEvent.MOUSE_DOWN, windowMouseDownHandler);
    }
  }

  public function removeWindow(window:Window):void
  {
    if (window == null)
    {
      throw new ArgumentError("Argument \"window\" cannot be null.");
    }
    var index:int = this._windows.indexOf(window);
    if (index != -1)
    {
      this._windows.splice(index, 1);
      this.removeChild(window);
      window.removeEventListener(MouseEvent.MOUSE_DOWN, windowMouseDownHandler);
    }
    else
    {
      throw new ArgumentError("Could not find argument \"window\" as child window.");
    }
  }

  public function selectWindow(window:Window):void
  {
    if (window != this.getChildAt(this.numChildren - 1))
    {
      this.removeChild(window);
      this.addChild(window);
    }
  }

  private function windowMouseDownHandler(event:MouseEvent):void
  {
    var window:Window = Window(event.currentTarget);
    selectWindow(window);
  }
}
}